package com.semidata.rtd.core.log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class BusinessLogHandler extends LogEventHandler {

    public static final String NAME = "BUSINESS";

    public BusinessLogHandler(LogBlockHandler handler) {
        super(handler);
    }

    @Override
    protected File getLogFile(LogEvent event, String root) {

        if (event.getType() != NAME)
            return null;

        Date date = new Date(event.getTimestamp());
        String dirName = new SimpleDateFormat("yyyyMMdd").format(date);
        String fileName = new SimpleDateFormat("HHmm").format(date);
        fileName = fileName.concat(".log");
        File dir = new File(new File(root, event.getType().toLowerCase()), dirName);
        if (dir.exists()) {
            if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
                return null;
        } else {
            if (!dir.mkdirs())
                return null;
        }
        File file = new File(dir, fileName);
        if (file.exists()) {
            if (!file.isFile() || !file.canWrite())
                return null;
        }
        return file;
    }

    @Override
    protected String getLogContent(LogEvent event) {
        if (event.getType() != NAME)
            return null;
        String content = event.getContent();
        if (!content.endsWith("\n"))
            content += '\n';
        return content;
    }

    @Override
    protected boolean verify(String root) {
        File dir = new File(root, NAME.toLowerCase());
        if (dir.exists()) {
            if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
                return false;
        } else {
            if (!dir.mkdirs())
                return false;
        }
        return true;
    }

}
